<?php
declare (strict_types = 1);

namespace app\command\logic;

use app\api\consDir\CommunityConst;
use app\command\logic\BaseLogic;
use app\command\logic\CliInterface;
use app\common\models\Community\CommunityOrder;
use app\common\models\Member\Account;
use app\common\models\Member\Member;
use app\common\models\Member\MemberProfitPoolLog;
use app\common\models\Member\MemberWithdraw;
use app\common\models\Member\StatsInviteManage;
use app\common\models\Order\Order;
use app\common\models\Order\OrderPay;
use app\common\models\Order\OrderShop;
use app\common\models\Shop\Shop;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 统计-会员推荐管理
 * php think cli stats_invite_manage --msg='{"days":30}'
 */
class CliStatsInviteManageLogic extends BaseLogic implements CliInterface
{

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function run(Output $output, array $msg): bool
    {
        $insertData = [];
        //$date       = $msg['date'] ?? '';
        $date       = isset($msg['date']) ? ($msg['date'] == 'today' ? date('Y-m-d') : $msg['date']) : null;
        if ( ! empty($date)) {
            self::dataForInviteManage($date);
        } else {
            $days = intval($msg['days'] ?? 1);
            for ($i = 1; $i <= $days; $i++) {
                $date = date('Y-m-d', strtotime("-$i days"));
                self::dataForInviteManage($date);
            }
        }
        return true;
    }


    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function dataForInviteManage($date): bool
    {
        $end = $date . ' 23:59:59';

        $list = Member::getInstance()->where('deleted',0)->select();
        foreach($list as $v){
            dump($v['id']);
            try{
                //会员直推荐会员的人数
                $where = [
                    ['invite_id','=',$v['id']],
                    ['create_at','between', [$date, $end]]
                ];
                $userNum = Member::getInstance()->where($where)->count();

                $where = [
                    ['invite_id','=',$v['id']],
                    ['create_at','between', [$date, $end]]
                ];

                //直推荐会员实名认证的人数
                $ids = Member::getInstance()->where($where)->column('id');
                $where = [
                    ['user_id','in',implode(',',$ids)],

                ];
                $whereOr = [
                    ['idc','<>',''],
                ];
                $userRealNum = Account::getInstance()->where($where)->where(function ($query) use ($whereOr) {
                    $query->whereOr($whereOr)->whereOr('idc is not null');
                })->count();

                //团队新增人数
                $teamNum = Member::getInstance()
                    ->whereLike('invite_ids','%-'.$v['id'].'-%')
                    ->where('create_at','between',[$date, $end])
                    ->count();

                //团队实名人数
                $teamRealNum = Member::getInstance()->alias('m')
                    ->leftJoin('member_account a','m.id=a.user_id')
                    ->whereLike('m.invite_ids','%-'.$v['id'].'-%')
                    ->where('m.create_at','between',[$date, $end])
                    ->where(function ($query) use ($whereOr) {
                        $query->whereOr('a.idc', '<>' , '')->whereOr('a.idc is not null');
                    })->count();

                //直推商家数
                $where = [
                    ['is_shop','=',1],
                    ['invite_id','=',$v['id']],
                    ['create_at','between', [$date, $end]]
                ];
                $shopNum = Member::getInstance()->where($where)->count();

                //团队商家数
                $teamShopNum = Member::getInstance()
                    ->where('is_shop',1)
                    ->whereLike('invite_ids','%-'.$v['id'].'-%')
                    ->where('create_at','between',[$date, $end])
                    ->count();

                //今日直推参与社区人数
                $where = [
                    ['m.invite_id','=',$v['id']],
                    ['o.status','=',CommunityConst::ORDER_PAY],
                    ['o.create_at','between', [$date, $end]]
                ];
                $inviteCommunityNum = CommunityOrder::getInstance()
                    ->alias('o')
                    ->leftJoin('member m','o.user_id=m.id')
                    ->where($where)
                    ->count();

                //今日团队会员参与社区人数
                $inviteTeamCommunityNum = CommunityOrder::getInstance()
                    ->alias('o')
                    ->leftJoin('member m','o.user_id=m.id')
                    ->whereLike('m.invite_ids','%-'.$v['id'].'-%')
                    ->where('o.create_at','between',[$date, $end])
                    ->where('o.status',CommunityConst::ORDER_PAY)
                    ->count('DISTINCT o.user_id');


                //直推商家营业额
                $where = [
                    ['is_shop','=',1],
                    ['invite_id','=',$v['id']],
                    ['create_at','between', [$date, $end]]
                ];
                $shopUserIds = Member::getInstance()->where($where)->column('id');
                $shopIds = Shop::getInstance()->where('user_id','in',$shopUserIds)->column('id');
                //1待发货 2待收款 3已收货 4已完成
                $inviteShopMoney = OrderShop::getInstance()
                    ->where('shop_id','in',$shopIds)
                    ->where('status','in',[1,2,3,4])
                    ->where('create_at','between',[$date, $end])
                    ->sum('pay_price') ?: 0;
                if($userNum <= 0 && $userRealNum <= 0 && $teamNum <= 0 && $teamRealNum <= 0 && $shopNum <= 0 && $teamShopNum <= 0 && $inviteCommunityNum <= 0 && $inviteTeamCommunityNum <= 0 && $inviteShopMoney <= 0){
                    continue;
                }
                $data = [
                    'user_num' => $userNum,
                    'user_real_num' => $userRealNum,
                    'team_num' => $teamNum,
                    'team_real_num' => $teamRealNum,
                    'shop_num' => $shopNum,
                    'team_shop_num' => $teamShopNum,
                    'invite_community_num' => $inviteCommunityNum,
                    'invite_team_community_num' => $inviteTeamCommunityNum,
                    'invite_shop_money' => $inviteShopMoney,
                    'user_id' => $v['id'],
                    'date' => $date,
                ];
                $where = [
                    ['date','=',$date],
                    ['user_id','=',$v['id']]
                ];
                $ret = StatsInviteManage::getInstance()->where($where)->find();
                if($ret){
                    $data['update_at'] = date('Y-m-d H:i:s');
                    StatsInviteManage::getInstance()->where($where)->update($data);
                }else{
                    StatsInviteManage::getInstance()->insert($data);
                }
            }catch (\Exception $ex){
                echo $ex->getMessage();
            }

        }
        return true;
    }
}
